/*** Created Time: 2022年5月12日 19:45:15 ***/
/*** Author: Eric                        ***/

#include <onix/string.h>

// 在C标准库中进行了assert断言检查，在此省略检查步骤

char *strcpy(char *dest, const char *src)
{
    char *ptr = dest;

    while(*src != EOS) {
        *ptr++ = *src++;
    }

    return dest;
}

char *strcat(char *dest, const char *src)
{
    char *ptr = dest;

    while(*ptr != EOS) {
        ptr++;
    }

    while(*src != EOS) {
        *ptr++ = *src++;
    }

    return dest;
}

size_t strlen(const char *str)
{
    char *ptr = (char *)str;

    while (*ptr != EOS) {
        ptr++;
    }

    return ptr - str;
}

int strcmp(const char *lhs, const char *rhs)
{
    while (*lhs == *rhs && *lhs != EOS && *rhs != EOS) {
        lhs++;
        rhs++;
    }

    return (*lhs < *rhs) ? -1 : (*lhs > *rhs);
}

char *strchr(const char *str, int ch)
{
    char *ptr = (char *)str;

    while (true) {
        if (*ptr == ch) {
            return ptr;
        }
        if (*ptr++ == EOS) {
            return NULL;
        }
    }
}

char *strrchr(const char *str, int ch)
{
    char *last = NULL;
    char *ptr = (char *)str;

    while (true) {
        if (*ptr == ch) {
            last = ptr;
        }

        if (*ptr++ == EOS) {
            return last;
        }
    }
}

int memcmp(const void *lhs, const void *rhs, size_t count)
{
    char *lptr = (char *)lhs;
    char *rptr = (char *)rhs;

    while (*lptr == *rptr && count-- > 0) {
        lptr++;
        rptr++;
    }

    return (*lptr < *rptr) ? -1 : (*lptr > *rptr);
}

void *memset(void *dest, int ch, size_t count)
{
    char *ptr = (char *)dest;

    while (count--) {
        *ptr++ = ch;
    }

    return dest;
}

void *memcpy(void *dest, const void *src, size_t count)
{
    char *ptr = (char *)dest;

    while (count--) {
        *ptr++ = *((char *)(src++));
    }

    return dest;
}

void *memchr(const void *str, int ch, size_t count)
{
    char *ptr = (char *)str;

    while (count--) {
        if (*ptr == ch) {
            return (void *)ptr;
        }
        
        ptr++;
    }
}